package com.cdh.oa.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cdh.oa.entity.*;
import com.cdh.oa.service.*;
import com.cdh.oa.util.ConstUtil;
import com.cdh.oa.util.MD5Util;
import com.cdh.oa.util.PinYinUtil;
import com.cdh.oa.util.ResponseData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author CDHong
 * @since 2018-11-22
 */
@Controller
@RequestMapping("/user")
@Slf4j
public class UserController {


    @Autowired private IRoleMenuBtnService roleMenuBtnService;
    @Autowired private IBtnService btnService;
    @Autowired private IUserService userService;
    @Autowired private IRoleService roleService;
    @Autowired private IJobService jobService;
    @Autowired private IDeptService deptService;

    @PostMapping("/del/{id}")
    public@ResponseBody ResponseData del(@PathVariable("id") Integer id){
        boolean flg = userService.removeById(id);
        if(flg){
            return ResponseData.okMsg("删除成功！！");
        }
        return ResponseData.fail("删除失败！！");
    }

    /**
     * 编辑和添加
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/edit")
    public @ResponseBody ResponseData edit(User user,HttpSession session){
        if(Objects.isNull(user.getId())){
            String logName = PinYinUtil.getPingYin(user.getRelName());
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.like("name",logName).orderByDesc("id");
            User usered = userService.getOne(queryWrapper);

            if(Objects.isNull(usered)){  //数据库中没有这个名字，则直接添加
                user.setName(logName);
            }else{ //如果有，则查看存在几个，如果只有一个，则加1
                String substring = usered.getName().substring(logName.length());
                if("".equals(substring)){
                    user.setName(logName+"1");
                }else{
                    int index = Integer.parseInt(substring)+1;
                    user.setName(logName+String.valueOf(index));
                }
            }
            //密码加密
            user.setPwd(MD5Util.getMD5(ConstUtil.DEFAULT_PWD));
            //添加人
            user.setCreateId(((User)session.getAttribute(ConstUtil.CURRENT_USER)).getId());
        }
        System.out.println(user);
        boolean flg = userService.saveOrUpdate(user);
        if(flg){
            return ResponseData.okMsg("更新成功！");
        }
        return ResponseData.fail("更新失败！");
    }


    /**
     * 添加-修改更新界面
     * @param model
     * @return
     */
    @GetMapping("/edit/page")
    public String edit(Model model){
        model.addAttribute("roles",roleService.list())
                .addAttribute("jobs",jobService.list())
                .addAttribute("depts",deptService.list());
        return "user/edit";
    }

    @GetMapping("/status")
    public @ResponseBody ResponseData editStatus(User user){
        boolean flg = userService.updateById(user);
        if(flg){
            return ResponseData.okMsg("更新成功！");
        }
        return ResponseData.fail("更新失败！");
    }

    /**
     * 分页查询
     * @param page 查询页面当前页码
     * @param limit  查询条数
     * @param search  查询条件
     * @return
     */
    @GetMapping("/list")
    public @ResponseBody ResponseData list(Integer page,Integer limit ,String search){
        return userService.userPage(page,limit,search);
    }

    @GetMapping("/index/{menuId}")
    public String index(@PathVariable("menuId") Integer menuId, HttpSession session, Model model){
        //获取用户所有权限
        User currUser = (User) session.getAttribute(ConstUtil.CURRENT_USER);
        //根据用户角色编号和模块编号查询对应的权限
        QueryWrapper<RoleMenuBtn> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("menu_id",menuId).and(qw->qw.eq("role_id",currUser.getRoleId()));
        List<Integer> btnIds = roleMenuBtnService.list(queryWrapper).stream().map(RoleMenuBtn::getBtnId).collect(Collectors.toList());
        Collection<Btn> btnList = btnService.listByIds(btnIds);

        log.debug("获取用户权限：menuId"+menuId+",roleId:"+currUser.getRoleId()+",权限信息："+btnIds.size());
        model.addAttribute("btnList",btnList);
        return "user/list";
    }

}
